<template>
  <div class="child-switcher">
    <template v-if="children.items.length">
      <van-picker
        :columns="pickerColumns"
        :default-index="defaultIndex"
        @confirm="onConfirm"
        @cancel="emit('close')"
      />
    </template>
    <template v-else>
      <div class="empty">
        <p>暂无儿童，请先创建</p>
        <van-button size="small" type="primary" @click="goSettings">去创建</van-button>
      </div>
    </template>
  </div>
</template>

<script setup lang="ts">
import { computed, onMounted } from 'vue'
import { useRouter } from '#app'
import { useChildrenStore } from '@/stores/children'

const emit = defineEmits(['close'])
const router = useRouter()
const children = useChildrenStore()

onMounted(() => {
  children.load()
})

const pickerColumns = computed(() => children.items.map(c => ({ text: c.name, value: c.id })))
const defaultIndex = computed(() => {
  const idx = children.items.findIndex(c => c.id === children.currentChildId)
  return idx >= 0 ? idx : 0
})

function onConfirm({ selectedOptions }: any) {
  const opt = selectedOptions?.[0]
  if (opt) {
    children.setCurrent(opt.value)
  }
  emit('close')
}

function goSettings() {
  emit('close')
  router.push('/settings')
}
</script>

<style scoped>
.child-switcher {
  padding: 16px;
}
.empty {
  text-align: center;
  padding: 24px 0;
  color: #6b7280;
}
.empty p {
  margin-bottom: 12px;
}
</style>

